<?php
/**
 * Created by PhpStorm.
 * User: 戎大富
 * Date: 2018/6/13
 * Time: 10:40
 */
namespace app\index\controller;
use think\Config;
use think\Controller;
use think\Db;

class  Base extends Controller {
    // 构造函数
    public function __construct(){
        parent::__construct();
        // 如果配置项为空 则直接返回
        if(!session('?openid2')){
//            $this->redirect(url('index/index/getuser'));
            $appid = config('wechat')['appid'];
            echo "<script> location.href='https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=http://we7.xuanwumobile.com/index/Auth2/getuser&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect'; </script>";
            exit;
        }else{
            $openid = session('openid2');
            $access_token = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$openid&lang=zh_CN";
            $res = json_decode($this->httpGet($url));
            if($res->subscribe == 0){
                header("Location: https://mp.weixin.qq.com/mp/profile_ext?action=home&__biz=MzIxNDAwODk5Mg==&subscene=0#wechat_redirect");
                exit;
            }else{
                $image = $res->headimgurl;
                $sex = $res->sex;
                $name = $res->nickname;
                $have = Db::table('up_u_user')->where('user_openid',$openid)->find();
                $info = [
                    'user_username' => $name,
                    'user_image' => $image,
                    'user_gender' => $sex,
                    'user_time' => date('Y-m-d H:i:s'),
                ];
                if($have){
                    Db::table('up_u_user')->where('user_openid',$openid)->update($info);
                }else{
                    $info['user_openid'] = $openid;
                    Db::table('up_u_user')->insert($info);
                }
            }
        }
    }
    //获取用户信息（数据库的）
    public function getUserInfo() {
        $openid = session('openid2');
        $user = Db::table('up_u_user')->where('user_openid',$openid)->find();
        return $user;
    }
    public function getAccessToken() {
        $appid = config('wechat')['appid'];
        $secret = config('wechat')['secret'];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
        $res = json_decode($this->httpGet($url));
        $access_token = $res->access_token;
        return $access_token;
    }

    /**
     * 同步公众号粉丝（不超过10000）
     */
    public function getUserList() {
        set_time_limit(0);
        $access_token = $this->getAccessToken();
        $id = '';
        $url2 = "https://api.weixin.qq.com/cgi-bin/user/get?access_token={$access_token}&next_openid=$id";
        $res2 = json_decode($this->httpGet($url2),true);
        $opendis = $res2['data']['openid']; // 这是当前公众号的前10000个用户的openid
        Db::table('up_u_user')->where('user_id','>',0)->delete();
        $access_token = $this->getAccessToken();
        foreach ($opendis as $k=>$v){
            $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=$access_token&openid=$v&lang=zh_CN";
            $res = json_decode($this->httpGet($url));
            $image = $res->headimgurl;
            $sex = $res->sex;
            $name = $res->nickname;
            $info = [
                'user_username' => $name,
                'user_image' => $image,
                'user_gender' => $sex,
                'user_time' => date('Y-m-d H:i:s'),
                'user_openid' => $v
            ];
            $res = Db::table('up_u_user')->insert($info);
            if(!$res){
                echo '同步出错，请刷新重试！';
            }
        }
        echo  '同步完成！';
    }
    public function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
//发送客服消息
    public function httpPost($url,$openid,$title,$content,$aid) {
        $att = $this->getAccessToken();
        $url .= $att;
        $q = "{$title}\n\n{$content}\n\n<a href='http://we7.xuanwumobile.com/index/Index/activitydatail?activity_id={$aid}'>点击查看详情</a>";
        $post_data = '{
    "touser":"'.$openid.'",
    "msgtype":"text",
    "text":
    {
         "content":"'.$q.'"
    }
}';
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);
        // 为保证第三方服务器与微信服务器之间数据传输的安全性，所有微信接口采用https方式调用，必须使用下面2行代码打开ssl安全校验。
        // 如果在部署过程中代码在此处验证失败，请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_HEADER, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
        curl_setopt($curl, CURLOPT_POST, 1);//post方法请求
        curl_setopt($curl, CURLOPT_POSTFIELDS, $post_data);//post请求发送的数据包
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
    public function getip() {
        $unknown = 'unknown';
        if(isset($_SERVER['HTTP_X_FORWARDED_FOR']) && $_SERVER['HTTP_X_FORWARDED_FOR'] && strcasecmp($_SERVER['HTTP_X_FORWARDED_FOR'], $unknown)){
            $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
        }elseif(isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], $unknown)) {
            $ip = $_SERVER['REMOTE_ADDR'];
        }
        /**
         * 处理多层代理的情况
         * 或者使用正则方式：$ip = preg_match("/[\d\.]{7,15}/", $ip, $matches) ? $matches[0] : $unknown;
         */
        if (false !== strpos($ip, ',')) $ip = reset(explode(',', $ip));
        return $ip;
    }

}